import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

var router = new Router({
  routes: [
    { path: '/login', name: 'login', component: () => import('@/views/login') },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/home'),
      redirect: '/welcome',
      children: [
        {
          path: '/welcome',
          name: 'welcome',
          component: () => import('@/views/welcome')
        }
      ]
    }
  ]
})
// 设置前置路由，在组件加载之前进行业务逻辑判断，使用beforeEach()
router.beforeEach((to, from, next) => {
  // to.path 为将要跳转的组件路由接口
  // from.path 为从哪个路由接口跳转
  // next('/home')转移其他路径, next()必须使用
  // console.log(to)
  // console.log(from)
  // next()

  // 如果用户是非登录状态，而且还要访问非登录页面，强制跳转到登录页面
  let token = window.sessionStorage.getItem('token')
  if (!token && to.path !== '/login') {
    return next('/login')
  }
  next()
})
// 设置router接收对象，需在后面将router导出
export default router
